package batch.common.secui;

import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import batch.common.util.*;

public class TripleDES {
    private SecretKey secretKey;
    private Cipher cipher;

    public TripleDES(String sKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        secretKey = SecretKeyFactory.getInstance("DESede").generateSecret(new DESedeKeySpec(sKey.getBytes()));
        cipher = Cipher.getInstance("DESede/ECB/NoPadding");
    }

    public String encrypt(String s) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        int j = s.length() % 8;
        if (j != 0) for (int i=0 ; i<8-j ; i++) s += " ";

        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return HexUtil.bytesToHex(cipher.doFinal(s.getBytes()));
    }

    public String decrypt(String s) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(HexUtil.hexToBytes(s))).trim();
    }
}
